
package com.catsic.zcjc.web.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.catsic.base.annotation.Log;
import com.catsic.base.controller.BaseController;
import com.catsic.pub.drawer.service.DrawerService;
import com.catsic.pub.form.DrawerForm;
import com.catsic.zcjc.condition.EquipMaintainCondition;
import com.catsic.zcjc.constants.ZcjcConstants;
import com.catsic.zcjc.entity.EquipMaintain;
import com.catsic.zcjc.entity.MaintainDataFile;
import com.catsic.zcjc.form.EquipMaintainForm;
import com.catsic.zcjc.form.ListForm;
import com.catsic.zcjc.service.EquipMaintainService;
import com.catsic.zcjc.service.MaintainDataFileService;


@Controller
@RequestMapping("/equipMaintain")
public class EquipMaintainController extends BaseController{

	private static String maintain_file_base_path="/opt/zcjc/maintain/";
	@Autowired
	private EquipMaintainService maintainService;
	@Autowired
	private MaintainDataFileService dataFileService;

	@Autowired
	private DrawerService drawerService;
	
    /**
     * 查询维护记录
	 * @author xietiebing
	 * @param condition 
	 * @return
	 */
	@RequestMapping(value = "/query" , method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> query(EquipMaintainCondition condition, Pageable  pageable){
		Page<EquipMaintainForm> page = maintainService.findAll(condition, pageable);
		Map<String,Object> map = new HashMap<String,Object>(); 
		map.put(CONTENT, page);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}
	
	/**
	 * create:创建
	 * @author xietiebing
	 * @param form
	 * @return
	 */
	@RequestMapping(value = "/create" , method = RequestMethod.POST)
	@ResponseBody
	@Log(module = "设备维护管理", operation = "添加维护记录")
	public Map<String,Object> create(EquipMaintainForm form, @RequestParam("attachment") CommonsMultipartFile attachment){
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String maintainTimeStr = form.getMaintainTimeStr();
			Date maintainTime = new Date();
			if(StringUtils.isNotBlank(maintainTimeStr)){
				maintainTime = df.parse(maintainTimeStr);
			}
			form.setMaintainTime(maintainTime);
			form.setCreateId(getCurrentUser().getUserId());
			form.setCreateName(getCurrentUser().getUsername());
			
			EquipMaintain maintain = maintainService.add(form);
			map.put(CONTENT, maintain);
			map.put(RESULT, RESULT_SUCCESS);
			if(attachment!=null){
				MaintainDataFile maintainDataFile = new MaintainDataFile();
				String equipCode = maintain.getEquip().getCode();
				String fileName = attachment.getFileItem().getName();
				File folder=new File(maintain_file_base_path + equipCode);
				if(!folder.exists()){
					folder.mkdirs();
				}
				String filePath = maintain_file_base_path + equipCode + "/" +fileName;

				maintainDataFile.setCreateId(getCurrentUser().getUserId());
				maintainDataFile.setCreateName(getCurrentUser().getUsername());
				
				maintainDataFile.setFileName(fileName);
				maintainDataFile.setFilePath(filePath);
				maintainDataFile.setMaintainData(maintain);
				dataFileService.add(maintainDataFile);
				File file = new File(filePath);
				file.createNewFile();
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(attachment.getBytes());
				fos.flush();
				fos.close();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * update:更新
	 * @author xietiebing
	 * @param form
	 * @return
	 */
	@RequestMapping(value = "/update" , method = RequestMethod.POST)
	@ResponseBody
	@Log(module = "设备维护管理", operation = "修改维护")
	public Map<String,Object> update(EquipMaintainForm form){
		form = maintainService.update(form);
		Map<String,Object> map = new HashMap<String,Object>(); 
		map.put(CONTENT, form);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}
	/**
	 * delete:删除
	 * @author xietiebing
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	@Log(module = "设备维护管理", operation = "删除维护")
	public Map<String,Object> delete(String id){
		maintainService.delete(id);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(RESULT,RESULT_SUCCESS);
		return map;
	}

	/**
	 * detail:维护主题列表
	 * @author xietiebing
	 * @param 
	 * @return
	 */
	@RequestMapping(value = "/typeList" , method = RequestMethod.GET)
	@ResponseBody
	public Map<String,Object> typeList(){
		List<DrawerForm> drawerList = drawerService.findByParentCode(ZcjcConstants.DRAWER_EQUIP_MAINTAIN_THEME_TYPE);
		
		List<ListForm> list = new ArrayList<ListForm>();
		for(DrawerForm drawer : drawerList){
			ListForm form = new ListForm();
			form.setId(drawer.getValue());
			form.setText(drawer.getName());
			
			list.add(form);
		}
		
		Map<String,Object> map = new HashMap<String,Object>(); 
		map.put(CONTENT, list);
		map.put(RESULT, RESULT_SUCCESS);
		return map;
	}

	@RequestMapping(value = "/download.json", method = RequestMethod.GET)
	@Log(module = "设备维护管理", operation = "下载附件")
	public void download(
			@RequestParam(value = "maintainId") String maintainId,
			HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		MaintainDataFile dataFile = dataFileService.findByMaintainId(maintainId);
		if(dataFile!=null){
			File file = new File(dataFile.getFilePath());
			response.setCharacterEncoding("utf-8");
			response.setContentType("multipart/form-data");
			response.setHeader("Content-Disposition", "attachment;fileName=\"" + dataFile.getFileName() + "\"");
			try {
				InputStream inputStream = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte[] b = new byte[1024];
				int length;
				while ((length = inputStream.read(b)) > 0) {
					os.write(b, 0, length);
				}
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
           response.setHeader("content-type", "text/html;charset=UTF-8");
            try {
                String data = "该记录无附件！";
                OutputStream outputStream = response.getOutputStream();
                byte[] dataByteArr = data.getBytes("UTF-8");
                outputStream.write(dataByteArr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
	}
}
